package bs_z7;

import java.util.concurrent.Semaphore;

public class Document {

	private Semaphore reader = new Semaphore(1);
	private Semaphore writer = new Semaphore(1);
	private Semaphore readerMutex = new Semaphore(1);
	private Semaphore writerMutex = new Semaphore(1);
	private Semaphore mutex = new Semaphore(1);
	private int readercount = 0, writercount = 0;
	
	public void reader(Reader reader) throws InterruptedException{
		this.mutex.acquire();
		this.reader.acquire();
		this.readerMutex.acquire();
		readercount++;
		if(readercount == 1)
			this.writer.acquire();
		this.readerMutex.release();
		this.reader.release();
		this.mutex.release();
		reader.read();
		this.readerMutex.acquire();
		readercount--;
		if(readercount == 0)
			this.writer.release();
		this.readerMutex.release();
	}
	
	public void writer(Writer writer) throws InterruptedException{
		this.writerMutex.acquire();
		writercount++;
		if(writercount == 1)
			this.reader.acquire();
		this.writerMutex.release();
		
		this.writer.acquire();
		writer.write();
		this.writer.release();
		this.writerMutex.acquire();
		writercount--;
		if(writercount == 0);
			this.reader.release();
		this.writerMutex.release();
		
	}
}
